package top.laoshuzi.server.userservice.provider;

import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.laoshuzi.server.userservice.service.UserService;

@Component
public class ThriftServiceProvider {

    @Value("${thrift.user-service.ip}")
    private String userServiceIp;
    @Value("${thrift.user-service.port}")
    private int userServicePort;

    public UserService.Client getUserService() throws TTransportException {
        return getService(userServiceIp, userServicePort, ServiceType.USER);
    }

    private <T> T getService(String ip, int port, ServiceType serviceType) throws TTransportException {
        TSocket socket = new TSocket(ip, port, 3000);

        TTransport transport = new TFramedTransport(socket);
        transport.open();

        TProtocol protocol = new TBinaryProtocol(transport);

        TServiceClient result = null;
        switch (serviceType) {
            case USER:
                result = new UserService.Client(protocol);
                break;
        }
        return (T) result;
    }

    private enum ServiceType {
        USER
    }
}
